const { ethers } = require("hardhat");

async function main() {
    console.log("🎯 NFT拍卖市场交互脚本");

    // 读取部署信息
    const fs = require('fs');
    let deploymentInfo;

    try {
        const data = fs.readFileSync('deployment-info.json', 'utf8');
        deploymentInfo = JSON.parse(data);
        console.log("📄 已加载部署信息");
    } catch (error) {
        console.error("❌ 无法读取部署信息，请先运行部署脚本");
        process.exit(1);
    }

    // 获取合约实例
    const [owner, seller, bidder1, bidder2] = await ethers.getSigners();

    const priceOracle = await ethers.getContractAt("PriceOracle", deploymentInfo.contracts.PriceOracle);
    const auctionNFT = await ethers.getContractAt("AuctionNFT", deploymentInfo.contracts.AuctionNFT);
    const auctionFactory = await ethers.getContractAt("AuctionFactory", deploymentInfo.contracts.AuctionFactory);

    console.log("🔗 已连接到合约:");
    console.log("  PriceOracle:", priceOracle.address);
    console.log("  AuctionNFT:", auctionNFT.address);
    console.log("  AuctionFactory:", auctionFactory.address);

    try {
        // 1. 查询当前ETH价格
        console.log("\n💰 查询当前价格...");
        const ethPrice = await priceOracle.getETHPrice();
        console.log("ETH价格:", ethers.utils.formatUnits(ethPrice, 8), "USD");

        // 2. 铸造测试NFT
        console.log("\n🎨 铸造测试NFT...");
        const mintTx = await auctionNFT.connect(seller).mintNFT(
            seller.address,
            "ipfs://QmTestNFTForAuction123456789",
            { value: ethers.utils.parseEther("0.01") }
        );
        await mintTx.wait();

        const tokenId = await auctionNFT.totalSupply();
        console.log("✅ NFT铸造完成, Token ID:", tokenId.toString());

        // 3. 授权拍卖工厂
        console.log("\n🔑 授权拍卖工厂...");
        await auctionNFT.connect(seller).setApprovalForAll(auctionFactory.address, true);
        console.log("✅ 授权完成");

        // 4. 创建拍卖
        console.log("\n🏺 创建拍卖...");
        const startPrice = ethers.utils.parseEther("0.1");   // 0.1 ETH起拍
        const reservePrice = ethers.utils.parseEther("0.2"); // 0.2 ETH保留价
        const duration = 24 * 3600; // 24小时

        const createTx = await auctionFactory.connect(seller).createAuction(
            auctionNFT.address,
            tokenId,
            startPrice,
            reservePrice,
            duration
        );

        const createReceipt = await createTx.wait();
        const auctionCreatedEvent = createReceipt.events.find(e => e.event === "AuctionCreated");
        const auctionAddress = auctionCreatedEvent.args.auctionContract;

        console.log("✅ 拍卖创建完成");
        console.log("  拍卖合约地址:", auctionAddress);
        console.log("  起拍价:", ethers.utils.formatEther(startPrice), "ETH");
        console.log("  保留价:", ethers.utils.formatEther(reservePrice), "ETH");
        console.log("  持续时间:", duration / 3600, "小时");

        // 5. 获取拍卖合约实例
        const auction = await ethers.getContractAt("NFTAuction", auctionAddress);

        // 6. 查询拍卖状态
        console.log("\n📊 查询拍卖状态...");
        const status = await auction.getAuctionStatus();
        console.log("  是否活跃:", status.isActive);
        console.log("  是否结束:", status.isEnded);
        console.log("  剩余时间:", status.timeRemaining.toString(), "秒");
        console.log("  当前最高出价USD:", ethers.utils.formatUnits(status.highestBidUSD, 8));
        console.log("  当前获胜者:", status.currentWinner);

        // 7. 模拟出价
        console.log("\n💎 模拟出价过程...");

        // 第一个出价者出价 0.15 ETH
        console.log("出价者1 出价 0.15 ETH...");
        const bid1Tx = await auction.connect(bidder1).bidWithETH({
            value: ethers.utils.parseEther("0.15")
        });
        await bid1Tx.wait();
        console.log("✅ 出价1完成");

        // 第二个出价者出价 0.25 ETH
        console.log("出价者2 出价 0.25 ETH...");
        const bid2Tx = await auction.connect(bidder2).bidWithETH({
            value: ethers.utils.parseEther("0.25")
        });
        await bid2Tx.wait();
        console.log("✅ 出价2完成");

        // 8. 查询更新后的状态
        console.log("\n📈 更新后的拍卖状态...");
        const updatedStatus = await auction.getAuctionStatus();
        const highestBid = await auction.highestBid();

        console.log("  当前最高出价:", ethers.utils.formatEther(highestBid.amount), "ETH");
        console.log("  最高出价USD价值:", ethers.utils.formatUnits(updatedStatus.highestBidUSD, 8), "USD");
        console.log("  当前获胜者:", updatedStatus.currentWinner);

        // 9. 查询出价历史
        console.log("\n📜 出价历史...");
        const bidHistory = await auction.getBidHistory();
        for (let i = 0; i < bidHistory.length; i++) {
            const bid = bidHistory[i];
            console.log(`  出价${i + 1}:`);
            console.log(`    出价者: ${bid.bidder}`);
            console.log(`    金额: ${ethers.utils.formatEther(bid.amount)} ETH`);
            console.log(`    USD价值: ${ethers.utils.formatUnits(bid.usdValue, 8)} USD`);
            console.log(`    时间: ${new Date(bid.timestamp * 1000).toLocaleString()}`);
        }

        // 10. 查询工厂统计
        console.log("\n📊 拍卖市场统计...");
        const factoryStats = await auctionFactory.getAuctionStats();
        console.log("  总拍卖数:", factoryStats.total.toString());
        console.log("  活跃拍卖数:", factoryStats.active.toString());
        console.log("  已结算拍卖数:", factoryStats.settled.toString());
        console.log("  总交易量:", ethers.utils.formatUnits(factoryStats.volume, 8), "USD");

        // 11. 获取活跃拍卖列表
        console.log("\n📋 活跃拍卖列表...");
        const activeAuctions = await auctionFactory.getActiveAuctions();
        console.log("  活跃拍卖数量:", activeAuctions.length);

        for (let i = 0; i < activeAuctions.length; i++) {
            const auctionSummary = activeAuctions[i];
            console.log(`  拍卖${i + 1}:`);
            console.log(`    合约地址: ${auctionSummary.auctionContract}`);
            console.log(`    卖家: ${auctionSummary.seller}`);
            console.log(`    NFT: ${auctionSummary.nftContract} #${auctionSummary.tokenId}`);
            console.log(`    起拍价: ${ethers.utils.formatEther(auctionSummary.startPrice)} ETH`);
            console.log(`    当前出价: ${ethers.utils.formatUnits(auctionSummary.currentBidUSD, 8)} USD`);
            console.log(`    结束时间: ${new Date(auctionSummary.endTime * 1000).toLocaleString()}`);
        }

        // 12. 演示价格转换功能
        console.log("\n💱 价格转换演示...");
        const ethAmount = ethers.utils.parseEther("1.0");
        const usdValue = await priceOracle.convertETHToUSD(ethAmount);
        console.log(`1 ETH = ${ethers.utils.formatUnits(usdValue, 8)} USD`);

        // 13. 检查合约升级能力
        console.log("\n🔧 检查升级功能...");
        console.log("合约支持UUPS升级模式");
        console.log("升级权限由合约所有者控制");

        // 14. 输出交互总结
        console.log("\n" + "=".repeat(50));
        console.log("🎯 交互测试完成!");
        console.log("=".repeat(50));
        console.log("✅ 价格查询正常");
        console.log("✅ NFT铸造成功");
        console.log("✅ 拍卖创建成功");
        console.log("✅ 出价功能正常");
        console.log("✅ 状态查询正常");
        console.log("✅ 统计功能正常");
        console.log("=".repeat(50));

        // 15. 下一步操作建议
        console.log("\n💡 下一步操作建议:");
        console.log("1. 等待拍卖时间结束");
        console.log("2. 调用 settleAuction() 结算拍卖");
        console.log("3. 验证NFT转移和资金分配");
        console.log("4. 测试其他高级功能");

        console.log("\n🔗 在Etherscan上查看:");
        console.log(`拍卖合约: https://sepolia.etherscan.io/address/${auctionAddress}`);

    } catch (error) {
        console.error("\n❌ 交互失败:", error);
        process.exit(1);
    }
}

main()
    .then(() => {
        console.log("\n🎊 交互完成!");
        process.exit(0);
    })
    .catch((error) => {
        console.error("❌ 交互脚本执行失败:", error);
        process.exit(1);
    });
